package com.ys.chatserver.rtc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.utils.LoggerFactory;
import com.ys.chatserver.common.dto.cnst.UserProtocalsType;
import com.ys.chatserver.http.logic.LogicProcessor2;
import org.slf4j.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class RtcOnPushPlayServlet extends HttpServlet {
    Logger logger = LoggerFactory.getLog();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            dispatch(JSONObject.parseObject(req.getReader().readLine(), RtcOnPushPlay.class), resp);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    protected void dispatch(RtcOnPushPlay prRequest, HttpServletResponse resp) throws IOException {
        System.out.println(JSON.toJSONString(prRequest));
        logger.info("-------------------------------------------------------------------push---------------------------------------------------------");
        String params = prRequest.getParams();
        String[] streamParams = getStreamParams(params);
        if (!CommonUtils.isStringEmpty(prRequest.getApp())) {
            if (prRequest.getApp().equals(ConstRtcApp.APP_LIVE)) { //上推视频
                if (streamParams[0].equals(ConstRtcApp.USER)) {
                    if (streamParams.length == 4) {
                        String groupId = streamParams[1];
                        String userId = streamParams[2];
                        //权限鉴定
                        resp.getWriter().write(authCheck(groupId, userId) ? RtcCommonAck.authSuccess() : RtcCommonAck.authFailure());
                    } else {
                        resp.getWriter().write(RtcCommonAck.authFailure());
                    }
                } else if (streamParams[0].equals(ConstRtcApp.DEV)) {
                    if (streamParams.length >= 3) {
                        String userId = streamParams[1];
                        //权限鉴定
                        resp.getWriter().write(authCheck(userId) ? RtcCommonAck.authSuccess() : RtcCommonAck.authFailure());
                    } else {
                        resp.getWriter().write(RtcCommonAck.authFailure());
                    }
                } else {
                    resp.getWriter().write(RtcCommonAck.authFailure());
                }

            } else if (prRequest.getApp().equals(ConstRtcApp.APP_PTT)) {//实时对讲
                if (streamParams.length >= 5) {
                    String s1;
                    String groupId;
                    String userId;
                    if (params.contains("SOS")) {//全频对讲
                        groupId = streamParams[2];
                        userId = streamParams[4];
                        s1 = groupId;
                    } else if (params.contains("ONEKEY")) {
                        //一键到底  头+SOS+群ID+级别+用户ID+时间戳
                        groupId = streamParams[2];
                        userId = streamParams[4];
                        s1 = groupId;
                    } else {
                        //频道对讲 头+群ID+频道ID+用户ID+时间戳
                        groupId = streamParams[1];
                        String channelId = streamParams[2];
                        userId = streamParams[3];
                        s1 = groupId + "-" + channelId;
                    }
                    if (authCheck(groupId, userId)) { //权限鉴定
                        Map<String, AtomicInteger> map = UserProtocalsType.SOS_NUMBER_MAP;
                        AtomicInteger num = map.get(s1);
                        if (Objects.isNull(num)) {
                            map.put(s1, new AtomicInteger(1));
                        } else {
                            num.addAndGet(1);
                            map.put(s1, num);
                        }
                        resp.getWriter().write(RtcCommonAck.authSuccess());
                    } else {
                        resp.getWriter().write(RtcCommonAck.authFailure());
                    }
                } else if (streamParams.length == 4) {
                    resp.getWriter().write(RtcCommonAck.authSuccess());
                } else {
                    resp.getWriter().write(RtcCommonAck.authFailure());
                }
            } else if (prRequest.getApp().equals(ConstRtcApp.APP_VOICE)) {
                resp.getWriter().write(RtcCommonAck.authSuccess());
            } else {
                resp.getWriter().write(RtcCommonAck.authFailure());
            }
        } else {
            resp.getWriter().write(RtcCommonAck.authFailure());
        }
        LoggerFactory.getLog().info("[RtcOnPushPlay]   -> " + prRequest);
        resp.setStatus(200);
    }

    /**
     * 获取stream参数
     *
     */
    private String[] getStreamParams(String params) {
        String[] strings = params.split("&");
        StringBuilder sb = new StringBuilder();
        for (String string : strings) {
            if (string.contains("stream")) {
                sb.append(string);
                break;
            }
        }
        String strData = sb.toString();
        if (!CommonUtils.isStringEmpty(strData)) {
            String[] strArray = strData.split("=");
            if (strArray.length >= 2) {
                String s = strArray[1];
                return s.split("-");
            } else {
                return new String[0];
            }
        } else {
            return new String[0];
        }
    }

    /**
     * 权限鉴定
     *
     * @param groupId 群组id
     * @param userId  用户id
     */
    private boolean authCheck(String groupId, String userId) {
        String[] arr = groupId.split("_");
        String sql = "select user_uid from chat_group_node where base_id ='" + arr[0] + "' and node_pid = '" + arr[1] + "'  and node_type = 'USER'";
        Vector<Vector<?>> vectors = null;
        try {
            vectors = LogicProcessor2.db.queryData(sql);

            if (vectors.isEmpty()) {//判断群组是否存在
                return false;
            } else {
                List<String> userList = new ArrayList<>();
                for (Vector<?> v : vectors) {
                    userList.add(v.get(0).toString());
                }
                if (!userList.contains(userId)) { //判断群组中是否存在该用户
                    return false;
                }
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 权限鉴定
     *
     * @param devId 设备id
     */
    private boolean authCheck(String devId) {
        String sql = "select user_uid from g_users where user_uid ='" + devId + "' and user_type = 1 and del_flag=0 and user_status=1";
        Vector<Vector<?>> vectors = null;
        try {
            vectors = LogicProcessor2.db.queryData(sql);
            if (vectors.isEmpty()) {//设备是否存在
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }


}
